package com.openthinks.joyniproject.utils;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
 * 从xml加载配置系统内存中
 * @author ZhangWenLong
 *
 */
public class SQLConfigLoader {

	private static Logger logger = Logger.getLogger(SQLConfigLoader.class);
	
	private static Map<String,String> sqlMap = new HashMap<String,String>();
	
	public static void init(){
		String databaseType = Config.getProperty("database.type");
		String fileNameList =  Config.getProperty("sql.fileNameList");
		String sqlRootPath = Config.getRootPath() + "WEB-INF/classes/config/sql/" + databaseType + "/";  
		
		File root = new File(sqlRootPath);
		if (root.isDirectory()) {
			for (File file : root.listFiles(new FileNameFilter(fileNameList))) {
				if (file.isDirectory()) {
					continue;
				}
				String fileName = file.getName();
				if (!file.isDirectory()) {
					loadSQLXmlConfig(sqlRootPath + file.getName());
					logger.info("Load SQL from: " +fileName);
				}
			}
		}
	}
	
	private static void loadSQLXmlConfig(String fileName){
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(new FileInputStream(fileName));
            Element sqls = document.getRootElement();
            
            for (Iterator<?> iter = sqls.elementIterator(); iter.hasNext();) {
                Element sqlElement = (Element) iter.next();

                String id = sqlElement.attributeValue("id");
                String sql = sqlElement.getText();
                
                sqlMap.put(id, sql);
            }
        } catch (Exception e) {
            logger.error("读取xml配置文件失败",e);
        }
		
	}
	
	public static String getSQL(String sqlId) {
		return sqlMap.get(sqlId);
	}
}
